package week2;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Created by dyc on 2016/11/10.
 */
public class LinkStack<Item> extends AbstractStack<Item> {
    private Node first;
    @Override
    public void push(Item item) {
        Node oldFirst = first;
        first = new Node();
        first.data = item;
        first.next = oldFirst;
    }

    @Override
    public Item pop() {
        if (isEmpty())
            throw new NoSuchElementException();
        Item data = first.data;
        first = first.next;
        return data;
    }

    @Override
    public boolean isEmpty() {
        return first == null;
    }

    @Override
    public int size() {
        int size = 0;
        for (Item data : this)
            size++;
        return size;
    }

    @Override
    public Iterator<Item> iterator() {
        return new StackIterator();
    }

    private class StackIterator implements Iterator<Item>{
        Node current = first;
        @Override
        public boolean hasNext() {
            return current != null;
        }
        @Override
        public Item next() {
            Item data = current.data;
            current = current.next;
            return data;
        }
    }

    private class Node{
        Item data;
        Node next;
    }
}
